<template>
  <div class="contacts">
    <div class="contacts-tabs">
      <el-menu class="el-menu-vertical-demo contacts-menu">
        <el-scrollbar
          @scroll="handleScroll"
          height="100%"
          view-style="height: 100%;"
          ref="contactsMenu"
        >
          <el-menu-item
            v-for="(item, index) in displayedContacts"
            :key="index"
            :index="index"
            class="contactslist"
            @click="clickContacts(item)"
          >
            <el-badge
              :value="item.unread_count"
              :offset="[-15, 45]"
              :show-zero="false"
              style="width: 100%; height: 100%"
            >
              <div class="contactslist-con">
                <!-- {{ item.user_nick }} -->
                <div class="contactslist-con-left">
                  <el-avatar
                    v-if="item.board_img != ''"
                    :src="item.board_img"
                  />
                  <el-avatar v-else>{{
                    item.board_name != ""
                      ? item.board_name[0]
                      : item.user_nick[0]
                  }}</el-avatar>
                </div>
                <div class="contactslist-con-right">
                  <div style="font-size: 14px">
                    {{
                      item.board_name != "" ? item.board_name : item.user_nick
                    }}
                  </div>
                  <div class="lastmessage">
                    <span>{{
                      item.lastmessage == null ? "" : item.lastmessage
                    }}</span>
                  </div>
                </div>
                <div class="contactslist-con-time">
                  <div style="font-size: 12px; color: #909399">
                    {{ formatTimestamp(item.last_chat_time) }}
                  </div>
                </div>
              </div>
            </el-badge>
          </el-menu-item>
        </el-scrollbar>
      </el-menu>
    </div>

    <div
      style="flex: 1"
      class="contacts-content"
      v-loading="messageloading"
      element-loading-text="加载中..."
      :element-loading-spinner="svg"
      element-loading-svg-view-box="-10, -10, 50, 50"
    >
      <ChatMessage v-if="chatmessagedata && chatmessagedata.data" />
      <el-empty v-else description="暂无数据" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, provide, inject, computed } from "vue";
import ChatMessage from "@/views/message/chatmessage.vue";

import { ipc } from "@/utils/ipcRenderer";
import { ipcApiRoute } from "@/api/main.js";

const contactsList = inject<any>("contactsList");
const activeaccount = inject<any>("activeaccount");
const messageList = ref([]);
const messagenum = ref(0);
const chatmessagedata = ref({});
provide("chatmessagedata", chatmessagedata);
provide("messageList", messageList);
// const displayedContacts = computed(() => {
//   return contactsList.value.slice(0, 10); // 初始显示前10个联系人
// });
const displayedContacts = ref([]);
provide("displayedContacts", displayedContacts);
const contactsMenu = ref(null);

const messageloading = ref(false);
const svg = `
        <path class="path" d=" 
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `;

const formatTimestamp = (timestamp) => {
  const now = new Date();
  const date = new Date(timestamp * 1000); // 将秒数转换为毫秒

  // 获取日期的年、月、日
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // getMonth 返回的是0到11，所以要加1
  const day = date.getDate();

  // 获取小时和分钟
  const hours = date.getHours();
  const minutes = date.getMinutes();

  // 获取昨天的日期
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  const yesterdayYear = yesterday.getFullYear();
  const yesterdayMonth = yesterday.getMonth() + 1;
  const yesterdayDay = yesterday.getDate();

  // 今天的时间戳的开始时间和结束时间
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const todayEnd = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate() + 1
  );

  let period;
  if (hours >= 0 && hours < 6) {
    period = "凌晨";
  } else if (hours < 12) {
    period = "上午";
  } else if (hours < 18) {
    period = "下午";
  } else if (hours < 21) {
    period = "傍晚";
  } else {
    period = "晚上";
  }

  if (date >= todayStart && date < todayEnd) {
    // 如果是今天
    const hours2 = ("0" + date.getHours()).slice(-2);
    const minutes2 = ("0" + date.getMinutes()).slice(-2);
    const formattedTime = `${period}${hours2}:${minutes2}`;
    return formattedTime;
  } else if (
    date.getFullYear() === yesterdayYear &&
    date.getMonth() + 1 === yesterdayMonth &&
    date.getDate() === yesterdayDay
  ) {
    // 如果是昨天
    return "昨天";
  } else if (date.getFullYear() === now.getFullYear()) {
    // 如果是今年，但不是今天
    const formattedDate = `${month}月${day}日`;
    return formattedDate;
  } else {
    // 如果是去年或更早的时间
    const formattedDate = `${year}-${month}-${day}`;
    return formattedDate;
  }
};

const handleScroll = (event) => {
  let scrollTop = event.scrollTop;
  let clientHeight = contactsMenu.value.$el.clientHeight;
  let scrollHeight =
    contactsMenu.value.$el.children[0].children[0].scrollHeight;

  const scrollPercentage = (scrollTop + clientHeight) / scrollHeight;

  // 当滚动条接近底部（可以根据实际需要调整阈值），加载更多数据

  if (scrollPercentage > 0.9) {
    loadMoreContacts();
  }
};

const loadMoreContacts = () => {
  // // console.log(displayedContacts.value.length);
  // // console.log(messagenum.value);
  messagenum.value = displayedContacts.value.length - 1
  
  if (contactsList.value.length != displayedContacts.value.length) {
    const currentLength = displayedContacts.value.length;
    const nextContacts = contactsList.value.slice(
      currentLength,
      currentLength + 10
    );
    displayedContacts.value = [...displayedContacts.value, ...nextContacts];
    getmessage();
  } 
  // else {
  //   const currentLength = displayedContacts.value.length;
  //   const nextContacts = contactsList.value.slice(
  //     currentLength,
  //     currentLength + 10
  //   );
  //   displayedContacts.value = [...displayedContacts.value, ...nextContacts];
  // }
};

const getmessage = () => {
  if (messagenum.value < displayedContacts.value.length) {
    let data = displayedContacts.value.slice(
      messagenum.value,
      messagenum.value + 3
    );
    let idArray = data.map((obj) => obj.id);
    // console.log(idArray);
    ipc
      .invoke(ipcApiRoute.getAccountmessage, {
        ids: idArray,
        cookie: activeaccount.value.cookie,
        bid_rid: activeaccount.value.bid_rid,
      })
      .then((res) => {
        if (res != undefined) {
          // console.log(res);

          res.forEach((resitem) => {
            let b = 0;
            let bindex = 0;
            displayedContacts.value.forEach((item, index) => {
              if (item.id == resitem.id) {
                b = 1;
                bindex = index;
              }
            });
            if (b == 1) {
              let d = resitem.data;
              let a = JSON.parse(
                JSON.stringify(displayedContacts.value[bindex])
              );
              a.data = d;

              let hasId = messageList.value.some((obj) => obj.id === a.id);
              if (!hasId) {
                messageList.value.push(a);
              }

              let filteredMessages = resitem.data.filter(
                (msg) => msg.type !== "read" && msg.type !== "delete"
              );
              if (filteredMessages[filteredMessages.length - 1].type == "img") {
                displayedContacts.value[bindex].lastmessage = "傳送一張圖片";
              } else {
                let c = filteredMessages[filteredMessages.length - 1].msg;
                displayedContacts.value[bindex].lastmessage = c;
              }
            }
          });
          messagenum.value += 3;
          getmessage();
        } else {
          // console.log(res);
          setTimeout(() => {
            getmessage();
          }, 3000);
        }
      });
  } else {
    messagenum.value = displayedContacts.value.length - 1;
  }
};

// 点击聊天框
const clickContacts = (item) => {
  messageloading.value = true;
  chatmessagedata.value = {};
  setTimeout(() => {
    let activemessage = messageList.value.find((item2) => item2.id === item.id);

    if (activemessage == undefined) {
      let currentTimestamp = Math.floor(Date.now() / 1000);
      let oneDayInSeconds = 24 * 60 * 60; // 一天的秒数
      let timestamp32 = currentTimestamp + oneDayInSeconds;
      ipc
        .invoke(ipcApiRoute.getoldmessage, {
          timestamp: timestamp32,
          cookie: activeaccount.value.cookie,
          bid_rid: activeaccount.value.bid_rid,
          id: item.id,
        })
        .then((res) => {
          if (res != "") {
            let copyitem = JSON.parse(JSON.stringify(item));
            copyitem.data = JSON.parse(res);
            let hasId = messageList.value.some((obj) => obj.id === copyitem.id);

            if (!hasId) {
              messageList.value.push(copyitem);
              // console.log(copyitem);

              chatmessagedata.value = copyitem;
              messageloading.value = false;
            } else {
              let activemessage2 = messageList.value.find(
                (item2) => item2.id === item.id
              );
              chatmessagedata.value = activemessage2;
              messageloading.value = false;
            }
          } else {
            messageloading.value = false;
          }
        });
    } else {
      chatmessagedata.value = activemessage;
      messageloading.value = false;
    }
  }, 500);
};

const getwatchmessage = () => {
  ipc
    .invoke(ipcApiRoute.watchmessage, {
      cookie: activeaccount.value.cookie,
      bid_rid: activeaccount.value.bid_rid,
    })
    .then((res) => {
      // console.log(res);
    });

  ipc.on("message-from-main", (event, message) => {
    if (message.length > 0) {
      message.forEach((item) => {
        let userid = item.userid;
        let toid = item.to[0];
        let aid = "";
        if (userid == activeaccount.value.bid_rid) {
          aid = toid;
        } else {
          aid = userid;
        }
        addmessageList(item, aid);
        if (item.type != "read" && item.type != "delete") {
          let foundIndex = contactsList.value.findIndex(
            (item2) => item2.id === aid
          );
          if (foundIndex !== -1) {
            // 如果找到了，将该对象移动到数组的第一位
            const foundItem = contactsList.value[foundIndex];
            contactsList.value.splice(foundIndex, 1); // 先移除该对象
            foundItem.unread_count += 1;
            foundItem.last_chat_time = parseInt(item.timestamp);
            contactsList.value.unshift(foundItem); // 再插入到数组的第一位

            promotedisplayedContacts(item, aid, foundItem);
          } else {
            ipc
              .invoke(ipcApiRoute.getalonemessageuser, {
                cookie: activeaccount.value.cookie,
                bid_rid: activeaccount.value.bid_rid,
                id: aid,
              })
              .then((res) => {
                if (res != "") {
                  let jsonres = JSON.parse(res);
                  if (jsonres.length > 0) {
                    contactsList.value.unshift(jsonres[0]);
                    if (item.type == "img") {
                      jsonres[0].lastmessage = "傳送一張圖片";
                    } else {
                      jsonres[0].lastmessage = item.msg;
                    }
                    displayedContacts.value.unshift(jsonres[0]); // 再插入到数组的第一位

                    
                  }
                }

                // // console.log(res);
              });
          }
        }
      });
    }
    // 处理收到的消息
  });
};

const promotedisplayedContacts = (message, aid, foundItem2) => {
  let foundIndex2 = displayedContacts.value.findIndex(
    (item3) => item3.id === aid
  );

  if (foundIndex2 !== -1) {
    const foundItem = displayedContacts.value[foundIndex2];
    displayedContacts.value.splice(foundIndex2, 1); // 先移除该对象
    // foundItem.unread_count += 1
    if (message.type == "img") {
      foundItem.lastmessage = "傳送一張圖片";
    } else {
      foundItem.lastmessage = message.msg;
    }
    displayedContacts.value.unshift(foundItem); // 再插入到数组的第一位
  } else {
    // foundItem2.unread_count += 1
    if (message.type == "img") {
      foundItem2.lastmessage = "傳送一張圖片";
    } else {
      foundItem2.lastmessage = message.msg;
    }
    displayedContacts.value.unshift(foundItem2); // 再插入到数组的第一位
  }
};

const addmessageList = (message, aid) => {
  let foundIndex2 = messageList.value.findIndex((item3) => item3.id === aid);

  if (foundIndex2 !== -1) {
    const foundItem = messageList.value[foundIndex2];
    let foundIndex3 = foundItem.data.findIndex((item4) => item4.timestamp === message.timestamp);
    if (foundIndex3 == -1) {
      foundItem.data.push(message);
    }
  }
};

onMounted(() => {
  messagenum.value = 0;
  if (contactsList.value.length > 0) {
    displayedContacts.value = contactsList.value.slice(0, 10);
    // console.log(displayedContacts.value);
    // console.log(contactsList.value);
    // console.log(activeaccount.value);

    getmessage();
    getwatchmessage();
  }
});
</script>

<style scoped>
.contacts {
  width: 98%;
  height: 100%;
  padding-left: 5px;
  display: flex;
}

.contacts-tabs {
  min-width: 250px;
  width: 30%;
  height: 95%;
}

.contacts-tabs-search {
  height: 10%;
  min-height: 60px;
  border-right: 1px solid #dcdfe6;
}

.contacts-tabs-search-ibs {
  display: flex;
  align-items: center;
}

.contacts-tabs-input {
  flex: 1;
  margin: 10px 5px;
}

.contacts-menu {
  height: 100%;
  margin-top: 10px;
}

.contactslist {
  border-bottom: 1px solid #dcdfe6;
  border-left: 1px solid #dcdfe6;
  height: 80px;
}

.contactslist:first-child {
  border-top: 1px solid #dcdfe6;
}

.contactslist-con {
  width: 100%;
  height: 100%;
}

.contactslist-con {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
.contactslist-con-left {
  display: flex;
  align-items: center;
}
.contactslist-con-right {
  height: 100%;
  flex: 1;
  overflow-x: hidden;
  margin-left: 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: start;
}
.contactslist-con-right div {
  height: 15px !important;
  line-height: 15px !important;
}
.contactslist-con-time {
  display: flex;
  align-items: flex-start;
  justify-content: flex-end;
  height: 100%;
  width: 60px;
}
.contactslist-con-time div {
  padding-top: 8px;
  height: 15px !important;
  line-height: 15px !important;
}

.contacts-content {
  display: flex;
  overflow: hidden;
  height: 100%;
  width: 100%;
  justify-content: center;
  align-items: center;
}

.lastmessage {
  font-size: 12px;
  color: #909399;
  width: 100%;
  display: flex;
}
.lastmessage span {
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>